class PromiseA {
    constructor(cb = ()=>{}){
        this._state = 'pending'
        this._value = ''
        this._chained = []
        const resolve = res => {
            this._state = 'fulfilled'
            this._value = res

            for(let { onFulfilled} of this._chained){
                onFulfilled(res)
            }
            return res
        }

        const reject = res =>{
            this._state = 'rejected'
            this._value = res
            for(let { onRejected} of this._chained){
                onRejected(res)
            }
        }

        try{
            cb(resolve, reject)
        }catch(e){
            reject(e)
        }
        return this
    }
    then(onFulfilled, onRejected){
        if(this._state === 'fulfilled'){
            onFulfilled(this._value)
        }else if( this._state === 'rejected'){
            onRejected(this._value)
        }else{
            this._chained.push({onFulfilled, onRejected})
        }
        return this
    }
}

new PromiseA((resolve)=>{
    setTimeout(()=>{
        resolve('a')
    }, 300)
}).then((a)=>{
    console.log(a)
    return '123'

}).then((a) => {
    console.log('b', a);
})

new Promise((resolve)=>{
    setTimeout(()=>{
        resolve('a')
    }, 300)
}).then((a)=>{
    console.log(a)
    return '123'
}).then((a) => {
    console.log('b', a);
})